<template>
  <canvas id="canvas" ref="canvas"/>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import {AxesHelper, PerspectiveCamera, Scene, WebGLRenderer} from 'three'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'

// 渲染dom
let canvas = ref<HTMLCanvasElement>()

// 场景
let scene: Scene
// 相机
let camera: PerspectiveCamera
// 渲染器
let renderer: WebGLRenderer

onMounted(() => {
  init()
  copilot()
  initLight()
  initModel()

  render()
})

// 初始化
function init(): void {
  scene = new Scene()
  camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight)
  camera.position.set(10, 10, 10)
  camera.lookAt(0, 0, 0)
  scene.add(camera)
  // 新建轨道控制器
  let orbitControls = new OrbitControls(camera, canvas.value)
  // 设置轨道控制器最大距离
  orbitControls.maxDistance = 100
  renderer = new WebGLRenderer({
    canvas: canvas.value,
    // 设置抗锯齿
    antialias: true,
    // 对数深度缓冲区，避免两个面离的太近而产生闪烁
    logarithmicDepthBuffer: true
  })
  // 设置渲染像素，该值会改变canvas的宽度和高度为设置值
  renderer.setSize(window.innerWidth, window.innerHeight)
  // 设置渲染器像素比率为设备像素比率  比如值为2时，宽度100px显示大小为200px
  renderer.setPixelRatio(window.devicePixelRatio)

  window.onresize = () => {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
  }
}

// 初始化光源
function initLight():void {

}

// 初始化模型
function initModel():void {

}

// 渲染函数
function render(): void {
  requestAnimationFrame(render)

  renderer.render(scene, camera)
}

// 设置辅助工具
function copilot(): void {
  // 设置坐标轴
  let axes = new AxesHelper(5)
  scene.add(axes)
}
</script>
